/**
 * @desc
 * @Author: bitqiang<bitqiang@outlook.net>
 * @date 2018/7/8 12:35
 */

import Vue from 'vue'
import Vuex from 'vuex'
import actionTotalMinutes from '../services/save-total-minutes'
import saveProgram from '../services/program'
Vue.use(Vuex)

const store = new Vuex.Store({
  strict: true,
  state: {
    userInfo: {},
    project: [],
    totle: 0
  },
  mutations: {
    saveStore (state) {
      wx.setStorage({
        key: 'store',
        data: state
      })
    },
    getUserInfo (state, data) {
      state.userInfo = data
    },
    getStore (state) {
      try {
        let value = wx.getStorageSync('store')
        if (value) {
          Object.keys(value).forEach(item => {
            state[item] = value[item]
          })
        }
      } catch (e) {
        console.log('取store错误')
      }
    },
    updateProject (state, data) {
      state.project = data
    },
    addTotle (state, time) {
      state.totle = Number(state.totle) + Number(time)
      actionTotalMinutes(Number(time))
    },
    addProject (state, data) {
      if (data.index === -1) {
        delete data.index
        let res = saveProgram(data, 'add')
        console.log('res11', res)
        debugger
        state.project.push(data)
      } else {
        delete data.index
        let res = saveProgram(data, 'change')
        console.log('res11', res)
        state.project.splice(data.index, 1, data)
      }
    }
  },

  actions: {
    getUserInfo ({ commit, state }, data) {
      commit('getStore')
      commit('getUserInfo', data)
      commit('saveStore')
    },
    updateProject ({ commit, state }, data) {
      commit('updateProject', data)
      commit('saveStore')
    },
    addTotle ({ commit, state }, data) {
      commit('addTotle', data)
      commit('saveStore')
    },
    addItem async ({ commit, state }, data) {
      if (data.index === -1) {
        let res = await saveProgram(data, 'add')
        console.log('res11', res)
        commit('addProject', data)
      } else {
        let res = await saveProgram(data, 'change')
        console.log('res11', res)
        commit('addProject', data)
      }
    }
  }
})

export default store
